package com.unsiv.torch;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.ImageView;

/**
 * <p>
 * Main Window
 * </p>
 * 
 * @author fanzhen
 * @time 7:54:00 PM Aug 26, 2011
 * @email fanzhen.meng@gmail.com
 */
public class LedTorch extends Activity {
	private static final String TAG = "LedTorch";
	private static final int MODE_BRIGHTNESS = 0;
	private static final int MODE_STROBE = 1;
	private static final int MODE_CUSTOMIZE = 2;
	private int mCurrentMode = -1;
	private PowerManager.WakeLock mWakeLock;
	private SharedPreferences setting;
	private SharedPreferences led_mode;
	private Editor settingEditor;
	private int mFlag;
	private StrobeHandler strobeHandler;
	private CustomizeHandler customizeHandler;
	private ImageView image_light;
	private ImageView ibutton_information;
	private ImageView ibutton_program;
	private ImageView ibutton_help;
	private int customizeDelayIndex;
	private String[] customizeDelayValues;
	private boolean canCustomizeHandler = true;
	private boolean canStrobeHandler = true;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.led);
		setting = getSharedPreferences("setting", 0);
		settingEditor = setting.edit();
		led_mode = getSharedPreferences("led_mode", 0);
		// init components
		image_light = (ImageView) findViewById(R.id.main_light);
		image_light.setBackgroundResource(R.drawable.led001);
		ibutton_information = (ImageView) findViewById(R.id.main_information);
		ibutton_program = (ImageView) findViewById(R.id.main_program);
		ibutton_help = (ImageView) findViewById(R.id.led_help);
//		selectMode(0);
		// set action for button.
		image_light.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				canCustomizeHandler = false;
				canStrobeHandler = false;
				MyCamaraHelper.switchCameraFlashMode();
				if(MyCamaraHelper.isCameraFlashMode()){
					image_light.setBackgroundResource(R.drawable.led001);
				}else{
					image_light.setBackgroundResource(R.drawable.led000);
				}
				return true;
			}
		});
		image_light.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				selectMode(1);
			}
		});
		ibutton_information.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplication(), Information.class);
				startActivity(intent);
			}
		});
		ibutton_program.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplication(), Program.class);
				intent.putExtra("type", "led");
				startActivity(intent);
			}
		});
		ibutton_help.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplication(), Help.class);
				startActivity(intent);
			}
		});
		mWakeLock = getWakeLock();
		if(mWakeLock !=null)
			mWakeLock.acquire();
	}
	private PowerManager.WakeLock getWakeLock() {
		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
		return wl;
	}
	@Override
	protected void onResume() {
		super.onResume();
		selectMode(0);
	}
	@Override
	protected void onPause() {
		super.onPause();
		canCustomizeHandler = false;
		canStrobeHandler = false;
		if(strobeHandler!=null)strobeHandler=null;
		if(customizeHandler!=null)customizeHandler=null;
		MyCamaraHelper.turnOff();
	}
	@Override
	protected void onStop() {
		super.onStop();
		if(mWakeLock !=null)
		{
			mWakeLock.release();	
			mWakeLock = null;
		}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		canCustomizeHandler = false;
		canStrobeHandler = false;
		if(strobeHandler!=null)strobeHandler=null;
		if(customizeHandler!=null)customizeHandler=null;
	}
	private void selectMode(int flag){
		int currentModeId = setting.getInt("current_led_mode", 0);
//		Log.i("LedTorch", "currentModeId:"+String.valueOf(currentModeId));
		if(currentModeId!=0){
			int nextModeId = currentModeId;
			if(flag==1){
				nextModeId = calculateMode(currentModeId);
			}
			String nextMode = led_mode.getString(String.valueOf(nextModeId), "1");
			String[] nextModeValues  = nextMode.split(",");
//			Log.i("LedTorch", "nextModeID:"+nextModeValues[0]);
			if(nextModeValues[0].equals("brightness")){
				//set led brightness
				Log.i("LedTorch", "next:customize");
				mCurrentMode = MODE_BRIGHTNESS;
				canStrobeHandler = false;
				canCustomizeHandler = false;
				File light = new File("/sys/devices/platform/flashlight.0/leds/flashlight/brightness");
				if(light.exists()&&light.canWrite()){
					try {
			            BufferedWriter out = new BufferedWriter(new FileWriter(light));
			            out.write(String.valueOf(Integer.valueOf(nextModeValues[1])+28)+"\n");
			            out.close();
			        } catch(IOException ex) {
			        	ex.printStackTrace();
			        }
				}else{
					MyCamaraHelper.turnOn();
				}
			}if(nextModeValues[0].equals("strobe")){
				Log.i("LedTorch", "next:strobe");
				//set led strobe
				mCurrentMode = MODE_STROBE;
				canStrobeHandler = true;
				canCustomizeHandler = false;
				if(Long.parseLong(nextModeValues[1])>0){
					strobeLed(1000/((Long.parseLong(nextModeValues[1])+5)/10));
				}else{
					strobeLed(new Long(1000/5*10));
				}
			}if(nextModeValues[0].equals("customize")){
				//set screen customize
				Log.i("LedTorch", "next:customize");
				mCurrentMode = MODE_CUSTOMIZE;
				canCustomizeHandler = true;
				canStrobeHandler = false;
				mFlag = 1;
				customizeDelayIndex = 1;
				customizeDelayValues = nextModeValues;
				if(customizeDelayValues.length>1){
					customizeLed(Long.parseLong(customizeDelayValues[customizeDelayIndex]));
				}
			}
		}else{
			MyCamaraHelper.turnOn();
		}
	}
	private int calculateMode(int modeId){
		int nextModeId = 1;
		if(modeId<setting.getInt("led_mode_count",led_mode.getAll().size())){
			nextModeId = modeId + 1;
		}
		settingEditor.putInt("current_led_mode", nextModeId);
		settingEditor.commit();
		return nextModeId;
	}
	private void strobeLed(Long delay){
		if (mCurrentMode != MODE_STROBE||!canStrobeHandler) {
			return;
		}
		strobeHandler = new StrobeHandler();
		strobeHandler.sleep(delay);
		if (mFlag == 1) {
			image_light.setBackgroundResource(R.drawable.led003);
			MyCamaraHelper.turnOn();
			mFlag = 0;
		} else {
			image_light.setBackgroundResource(R.drawable.led001);
			MyCamaraHelper.turnOff();
			mFlag = 1;
		}
	}
	class StrobeHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle bundle =  msg.getData();
			strobeLed(bundle.getLong("delay"));
		}
		public void sleep(long delayMillis) {
			removeMessages(0);
			Message msg = new Message();
			Bundle data = new Bundle();
			data.putLong("delay", delayMillis);
			msg.setData(data);
			sendMessageDelayed(msg, delayMillis);
		}
	}
	private void customizeLed(long delay){
		if (mCurrentMode != MODE_CUSTOMIZE||!canCustomizeHandler) {
			return;
		}
		if (mFlag == 1) {
			image_light.setBackgroundResource(R.drawable.led003);
			MyCamaraHelper.turnOn();
			mFlag = 0;
		} else {
			image_light.setBackgroundResource(R.drawable.led001);
			MyCamaraHelper.turnOff();
			mFlag = 1;
		}
		customizeHandler = new CustomizeHandler();
		customizeHandler.sleep(delay);
	}
	class CustomizeHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle bundle =  msg.getData();
			customizeLed(bundle.getLong("delay"));
		}
		public void sleep(long delayMillis) {
			removeMessages(0);
			customizeDelayIndex = customizeDelayIndex+1;
			if(customizeDelayIndex==customizeDelayValues.length)
				customizeDelayIndex=1;
			if(customizeDelayIndex<customizeDelayValues.length){
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putLong("delay", Long.parseLong(customizeDelayValues[customizeDelayIndex]));
				msg.setData(data);
				sendMessageDelayed(msg, delayMillis);
			}
		}
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "Exit");
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			MyCamaraHelper.turnOff();
			new ActivityUtil(this).exit();
			return true;
		}
		return false;
	}
}